// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package androidx.gdata.contacts;

import org.w3c.dom.Node;

import java.io.IOException;
import java.net.URL;

import androidx.gdata.contacts.xml.ContactFeedDeserializer;
import androidx.gdata.LinkUrl;
import androidx.gdata.GDataServer;
import androidx.gdata.LinkUrlUtil;

/**
 * @author Mike Jennings
 */
final class ContactServerImpl extends GDataServer implements ContactServer {
  private static ContactFeedDeserializer feedBuilder = new ContactFeedDeserializer();

  ContactServerImpl(String baseUrl, String username, String auth) {
    super(baseUrl, username, auth);
  }

  /**
   * See http://code.google.com/apis/contacts/developers_guide_protocol.html#contacts_feed_url
   * @return
   * @throws IOException
   */
  public ContactFeed getContactFeed() throws IOException {
    URL url = new URL(getBaseUrl() + getUsername() + "/full");
    return toContactFeed(url);
  }

  private ContactFeed toContactFeed(URL url) throws IOException {
    String result = doAuthorizedGet(url);
    Node feedNode = extractFeedNode(result);
    return feedBuilder.build(feedNode);
  }

  public ContactFeed getSelf(ContactFeed feed) throws IOException {
    LinkUrl link = LinkUrlUtil.getSelf(feed);
    if (link == null) {
      throw new IOException("No self link found!");
    }
    URL url = new URL(link.getHref());
    return toContactFeed(url);
  }

  public ContactFeed getNext(ContactFeed feed) throws IOException {
    LinkUrl link = LinkUrlUtil.getNext(feed);
    if (link == null) {
      return null;
    }
    URL url = new URL(link.getHref());
    return toContactFeed(url);
  }


  
}
